package com.anuo.app.common.utils;


import com.anuo.app.common.entity.Request;
import com.anuo.app.common.entity.Response;
import com.anuo.app.common.globalhandle.AppException;
import com.anuo.app.modules.user.entity.UserAccount;
import com.anuo.app.modules.user.entity.UserFilter;
import com.fasterxml.jackson.core.type.TypeReference;
import okhttp3.*;


import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 常见http请求封装(封装的是OKhttp)
 * 调用实例见: ydlPostCall, studyOkHttpCall 方法
 * 参考(以下代码参考的是官网):http://square.github.io/okhttp/
 */
public class NetUtil {


    private static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    /**
     * 可以静态使用
     * 参考:https://stackoverflow.com/questions/30888240/okhttp-application-level-okhttpclient-instance
     */
    private static OkHttpClient client = new OkHttpClient();

    /**
     * 发送 get 请求
     *
     * @param url
     * @param result
     * @param <T>
     * @return 返回java类型
     */
    public static <T> T sendGet(String url, T result) {
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .get()
                .build();

        String rspStr = "";
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
            rspStr = response.body().string();

        } catch (IOException e) {
            throw new AppException("sendGet 请求失败",e);
        }

        result =JsonUtil.fromJson(rspStr,
                new TypeReference<T>() {
                });

        return result;
    }

    /**
     * 发送 get 请求
     * @param url
     * @return 返回请求结果(字符串)
     */
    public static String sendGet(String url) {
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .get()
                .build();

        String rspStr="";
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
            rspStr = response.body().string();

        } catch (IOException e) {
            throw new AppException("sendGet 请求失败",e);
        }
        return rspStr;
    }


    /**
     * 发送 post 请求
     *
     * @param url
     * @param result
     * @param jsonBody
     * @param <T>
     * @return
     */
    public static <T> T sendPost(String url, String jsonBody, T result) {
        RequestBody body = RequestBody.create(JSON, jsonBody);
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .build();

        String rspStr = "";
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
            rspStr = response.body().string();
        } catch (IOException e) {
            throw new AppException("sendPost 请求失败",e);
        }

        result = JsonUtil.fromJson(rspStr,
                new TypeReference<T>() {
                });
        return result;
    }

    private void ydlPostCall() {
        UserFilter userFilter = new UserFilter();
        userFilter.setCode("160000000083");
        Request<UserFilter> request = new Request();
        request.setToken("68aa38121bea724c85eec2f6d7e4871c");
        request.setVersion("1.9.0");
        //request.setEntities(userFilter);
        String reqBody = JsonUtil.toJson(request);

        Response<UserAccount> rsp = new Response<>();
        rsp = new NetUtil().sendYDLPost(rsp, "GetUserByCode", reqBody);
        List<UserAccount> list = rsp.getEntities();
        System.out.println(JsonUtil.toJsonPretty(list));
    }

    /**
     * 发送 ydl post 请求
     * 注: 使用示例见 HttpUtil 类 main 方法
     *
     * @param jsonBody
     * @return
     */
    private <T> Response<T> sendYDLPost(Response<T> result, String apiName, String jsonBody) {
        String url = "http://192.168.2.113:5031/WebSite/TestApi?serviceName=" + apiName;
        RequestBody body = RequestBody.create(JSON, jsonBody);
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .build();

        String rspStr = "";
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
            rspStr = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        result = JsonUtil.fromJson(rspStr,
                new TypeReference<Response<T>>() {
                });
        return result;
    }

    private void studyOkHttpCall() {
        //教程参考: http://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html#sending-and-receiving-network-calls
        //一般 sendPost 请求
        String url = "http://192.168.2.113/WebSite/TestApi?serviceName=GetVipBuy";
        String body = "{token:\"kdiwmmsabc\"}";
        //String rsp=new HttpUtil().sendPost(url,body);

        //拼接查询参数 比如: ?name=jk&age=27
        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
        urlBuilder.addQueryParameter("v", "1.0");
        urlBuilder.addQueryParameter("user", "vogella");
        //拼接path 比如 url后面加 v1/doc/okhttpdoc
        urlBuilder.addPathSegment("v1");
        urlBuilder.addPathSegment("doc");
        urlBuilder.addPathSegment("okhttpdoc");
        String url2 = urlBuilder.build().toString();

        //加header
        okhttp3.Request request = new okhttp3.Request.Builder()
                .header("Authorization", "your token")
                .header("UserId", "sssddd")
                .url("https://api.github.com/users/vogella")
                .build();

    }

    /**
     * 判断Ip是否有效
     *
     * @param ip
     * @return
     */
    public static boolean validIP(String ip) {
        try {
            if (ip == null || ip.isEmpty()) {
                return false;
            }

            String[] parts = ip.split("\\.");
            if (parts.length != 4) {
                return false;
            }

            for (String s : parts) {
                int i = Integer.parseInt(s);
                if ((i < 0) || (i > 255)) {
                    return false;
                }
            }
            if (ip.endsWith(".")) {
                return false;
            }

            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    /**
     * 获取服务器ip(就是本机ip)
     * @return
     * @throws UnknownHostException
     */
    public static String getServerIp()  {
        InetAddress ipObj = null;
        try {
            ipObj = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            //e.printStackTrace();
        }
        return ipObj.getHostAddress();
    }


}
